package com.zhoug.json2;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * Boolean序列化转化器
 *
 * @Author: zhoug
 * @Date: 2023/3/17
 * @Description:
 */
public class BooleanTypeAdapter extends TypeAdapter<Boolean> {

    @Override
    public void write(JsonWriter out, Boolean value) throws IOException {
        out.value(value);
    }

    @Override
    public Boolean read(JsonReader in) throws IOException {
        try {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return false;
            }
            try {
                boolean b = in.nextBoolean();
                return b;
            } catch (Exception e) {
                String result = in.nextString();
                if (result == null || result.trim().isEmpty()) {
                    return false;
                }
                result = result.trim().toLowerCase();
                if (result.contains("true")) {
                    return true;
                } else if (result.contains("false")) {
                    return false;
                } else if (result.equals("1")) {
                    return true;
                } else if (result.equals("0")) {
                    return false;
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
